package com.junzhiit.nengji.shop.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.bainaeco.framework.util.DateUtil;
import com.junzhiit.nengji.bo.ChargeRuleBO;
import com.junzhiit.nengji.bo.OrdersTransactionInfoBO;
import com.junzhiit.nengji.bo.ShopClientBO;
import com.junzhiit.nengji.dao.BalanceHistoryDAO;
import com.junzhiit.nengji.dao.ChargeRuleDAO;
import com.junzhiit.nengji.dao.MemberCardDAO;
import com.junzhiit.nengji.dao.MemberCardHistoryDAO;
import com.junzhiit.nengji.dao.OrdersDAO;
import com.junzhiit.nengji.dao.ShopClientDAO;
import com.junzhiit.nengji.dao.UserDAO;
import com.junzhiit.nengji.dao.WechatConfigDAO;
import com.junzhiit.nengji.dao.cache.ReservedCacheDAO;
import com.junzhiit.nengji.dao.cache.WechatConfigCacheDAO;
import com.junzhiit.nengji.dao.util.DIYKey;
import com.junzhiit.nengji.model.BalanceHistory;
import com.junzhiit.nengji.model.MemberCard;
import com.junzhiit.nengji.model.MemberCardHistory;
import com.junzhiit.nengji.model.ShopClient;
import com.junzhiit.nengji.model.User;
import com.junzhiit.nengji.model.WechatConfig;
import com.junzhiit.nengji.model.enums.BalanceHistoryOperation;
import com.junzhiit.nengji.model.enums.BalanceHistoryStatus;
import com.junzhiit.nengji.model.enums.Is;
import com.junzhiit.nengji.model.enums.MemberCardHistoryStatus;
import com.junzhiit.nengji.model.enums.MemberCardType;
import com.junzhiit.nengji.model.enums.MemberCardValidTime;
import com.junzhiit.nengji.model.enums.MemberLevelCode;
import com.junzhiit.nengji.model.enums.ShopClientStatus;
import com.junzhiit.nengji.shop.service.CouponsService;
import com.junzhiit.nengji.shop.service.MemberCardService;
import com.junzhiit.nengji.shop.web.exception.MemberCardAlreadyExistException;
import com.junzhiit.nengji.shop.web.exception.UserNotFoundException;
import com.junzhiit.nengji.shop.web.exception.WechatConfigAddException;
import com.junzhiit.nengji.shop.web.util.Constants;
import com.junzhiit.nengji.shop.web.util.OrderNumberUtils;
import com.junzhiit.nengji.shop.web.util.RequestUtil;
import com.junzhiit.nengji.shop.web.util.wechat.WeChatUtils;
import com.junzhiit.nengji.shop.web.util.wechat.bean.OrderInfo;
import com.junzhiit.nengji.shop.web.util.wechat.bean.PayParam;
import com.junzhiit.nengji.shop.web.vo.PurchaseMemberCardVO;
import com.junzhiit.nengji.shop.web.vo.RechargeMemberCardVO;
import com.junzhiit.nengji.shop.web.vo.ReservedVO;
import com.junzhiit.nengji.shop.web.vo.ResultVO;

@Service
public class MemberCardServiceImpl extends BaseServiceImpl implements MemberCardService {

	@Autowired
	private OrdersDAO ordersDAO;

	@Autowired
	private MemberCardDAO memberCardDAO;

	@Autowired
	private CouponsService couponsService;

	@Autowired
	private ShopClientDAO shopClientDAO;

	@Autowired
	private UserDAO userDAO;

	@Autowired
	private BalanceHistoryDAO balanceHistoryDAO;

	@Autowired
	private ChargeRuleDAO chargeRuleDAO;
	
	@Autowired
	private ReservedCacheDAO reservedCacheDAO;
	
	@Autowired
	private WechatConfigDAO wechatConfigDAO;
	
	@Autowired
	private WechatConfigCacheDAO wechatConfigCacheDAO;
	
	@Autowired
	private MemberCardHistoryDAO memberCardHistoryDAO;
	

	private final String WECHAT_BODY_KEY = "乐鸽订单";

	@Override
	public ResultVO findAll(ShopClientBO shopClientBO) {
		ResultVO result = new ResultVO();
		List<ShopClientBO> list = shopClientDAO.findAll(shopClientBO);
		result.setData(list);
		return result;
	}

	@Override
	public ResultVO getShopMemberCard(String csId) {
		ResultVO result = new ResultVO();
		List<MemberCard> list = memberCardDAO.findAllavAilable(csId);
		result.setData(list);
		return result;
	}

	@Override
	public ResultVO receive(String userId, String csId, String memberCardId) {
		ResultVO result = new ResultVO();
		Date now = new Date();
		MemberCard memberCard = memberCardDAO.query(memberCardId);
		
		if(memberCard == null){
			throw new MemberCardAlreadyExistException("会员卡不存在");
		}

		ShopClient shopClient = shopClientDAO.findClientByUserId(userId, csId);

		// 在商户会员表中添加记录
		if (shopClient == null) {
			
			//检查会员编号是否超出最大值
			String key = DIYKey.getReservedKey(csId);
			ReservedVO reservedVO = reservedCacheDAO.getHash(key, ReservedVO.class);
			String maxNumber = null;
			if(reservedVO == null){
				reservedVO = new ReservedVO();
				maxNumber = OrderNumberUtils.cardNumber(null, OrderNumberUtils.SHOP_CLIENT_DIGIT);
			}else{
				maxNumber = OrderNumberUtils.cardNumber(reservedVO.getMaxValue(), OrderNumberUtils.SHOP_CLIENT_DIGIT);
			}
			reservedVO.setMaxValue(maxNumber);
			reservedCacheDAO.addHash(key, reservedVO);
			
			shopClient = new ShopClient();
			shopClient.setCsId(csId);
			shopClient.setUserId(userId);
			shopClient.setMemberCardId(memberCard.getId());
			shopClient.setCardNumber(maxNumber);
			shopClient.setBalance(0d);
			shopClient.setNowIntegral(0);
			shopClient.setConsumeIntegral(0);
			shopClient.setGrade(memberCard.getGrade());
			shopClient.setClientStatus(ShopClientStatus.MEMBER.toIntStatus());
			shopClient.setClientDate(now);
			
			// 设置状态为有效
			if (memberCard.getValidTimeState() == MemberCardValidTime.FIXED.toIntStatus()) {
				shopClient.setMemberDate(memberCard.getValidStartTime());
				shopClient.setMemberEndDate(memberCard.getValidEndTime());
			} else if (memberCard.getValidTimeState() == MemberCardValidTime.PERIOD.toIntStatus()) {
				shopClient.setMemberDate(now);
				Date date = DateUtil.addDays(now, memberCard.getValidDays());
				shopClient.setMemberEndDate(date);
			}else{
				shopClient.setMemberDate(null);
				shopClient.setMemberEndDate(null);
			}

			if (memberCard.getIsPresentCoupon() == Is.YES.toIntValue()) {
				if (memberCard.getCouponsId() != null) {
					couponsService.insert(userId, memberCard.getCouponsId());
				}
			}
			result.setData(shopClientDAO.insert(shopClient));
		} else {
			if(shopClient.getClientStatus() == ShopClientStatus.UNMEMBER.toIntStatus()){
				shopClient.setMemberCardId(memberCard.getId());
				if (memberCard.getValidTimeState() == MemberCardValidTime.FIXED.toIntStatus()) {
					shopClient.setMemberDate(memberCard.getValidStartTime());
					shopClient.setMemberEndDate(memberCard.getValidEndTime());
				} else if (memberCard.getValidTimeState() == MemberCardValidTime.PERIOD.toIntStatus()) {
					shopClient.setMemberDate(now);
					Date date = DateUtil.addDays(now, memberCard.getValidDays());
					shopClient.setMemberEndDate(date);
				}else{
					shopClient.setMemberDate(null);
					shopClient.setMemberEndDate(null);
				}
				if (memberCard.getIsPresentCoupon() == Is.YES.toIntValue()) {
					if (memberCard.getCouponsId() != null) {
						couponsService.insert(userId, memberCard.getCouponsId());
					}
				}
				shopClient.setClientStatus(ShopClientStatus.MEMBER.toIntStatus());
				shopClient.setGrade(memberCard.getCardGrade());
				shopClientDAO.update(shopClient);
				result.setData(shopClient);
			}else{
				throw new MemberCardAlreadyExistException("已经领取过该店会员卡");
			}
		}
		return result;
	}

	@Override
	public ShopClient receiveByShop(String userId, String csId,Integer isChain) {
		Date now = new Date();
		/**
		 * 1.首先查寻出该店铺下得会员卡 
		 * 2.统计用户在该店铺下得消费次数以及消费金额 
		 * 3.查询用户是否已经领取过该店铺的会员卡
		 * 4.判断是否可以领取会员卡
		 */
		// 1.首先查寻出该店铺下得会员卡
		List<MemberCard> memberCardList = memberCardDAO.findAll(csId);
		// 2.查询用户是否已经领取过该店铺的会员卡
		ShopClient shopClient = shopClientDAO.findClientByUserId(userId, csId);
		// 3.统计用户在该店铺下得消费次数以及消费金额
		OrdersTransactionInfoBO ordersTransactionInfoBO = null;
		// 4.判断是否可以领取会员卡
		boolean receive = false;
		/**
		 * 1.如果用户没有领取过该店的会员卡 如果符合最低会员卡领取标准则领取该会员卡 
		 * 2.如果用户已经领取过该店会员卡 如果符合下一等级会员卡领取标准则领取该会员卡
		 */
		if (shopClient == null) {
			ordersTransactionInfoBO = ordersDAO.countUserTransaction(userId,csId,isChain,null);
			for (int i = 0, t = memberCardList.size(); i < t; i++) {
				MemberCard memberCard = memberCardList.get(i);
				if (memberCard.getType() == MemberCardType.ONE_LEVEL.toIntValue()) {
					if (memberCard.getCardGrade() != null
							&& memberCard.getCardGrade() == MemberLevelCode.STAIR.toIntValue()) {
						if (memberCard.getBuyCount() != null && memberCard.getBuyCount() > 0) {
							// 用户的累积交易次数 大于 该会员卡的可获得的交易次数
							if (ordersTransactionInfoBO.getCountTransaction() > memberCard.getBuyCount()) {
								receive = true;
							} else {
								receive = false;
								logger.info(userId + "：用户累积交易次数不符合[" + csId + "]最低会员卡领取标准");
								break;
							}
						}
						if (memberCard.getConsumePrice() != null && memberCard.getConsumePrice() > 0) {
							// 用户的累计交易金额 大于 该会员卡的可获得的交易金额数
							if (ordersTransactionInfoBO.getSumPayMoney() != null
									&& ordersTransactionInfoBO.getSumPayMoney() > 0
									&& ordersTransactionInfoBO.getSumPayMoney() > memberCard.getConsumePrice()) {
								receive = true;
							} else {
								receive = false;
								logger.info(userId + "：用户累积金额次数不符合[" + csId + "]最低会员卡领取标准");
								break;
							}
						}
						
						// 用户初次领取会员卡-->符合该店铺下最小等级的会员卡
						if (receive) {
							// 在商户会员表中添加记录
							String key = DIYKey.getReservedKey(csId);
							ReservedVO reservedVO = reservedCacheDAO.getHash(key, ReservedVO.class);
							String maxNumber = OrderNumberUtils.cardNumber(reservedVO.getMaxValue(), OrderNumberUtils.SHOP_CLIENT_DIGIT);
							reservedVO.setMaxValue(maxNumber);
							reservedCacheDAO.addHash(key, reservedVO);

							shopClient = new ShopClient();
							shopClient.setCsId(csId);
							shopClient.setUserId(userId);
							shopClient.setMemberCardId(memberCard.getId());
							shopClient.setCardNumber(maxNumber);
							shopClient.setBalance(0d);
							shopClient.setNowIntegral(0);
							shopClient.setConsumeIntegral(0);
							shopClient.setGrade(memberCard.getGrade());
							shopClient.setClientStatus(ShopClientStatus.MEMBER.toIntStatus());

							// 设置状态为有效
							if (memberCard.getValidTimeState() == MemberCardValidTime.FIXED.toIntStatus()) {
								shopClient.setMemberDate(memberCard.getValidStartTime());
								shopClient.setMemberEndDate(memberCard.getValidEndTime());
							} else if (memberCard.getValidTimeState() == MemberCardValidTime.PERIOD.toIntStatus()) {
								shopClient.setMemberDate(now);
								Date date = DateUtil.addDays(now, memberCard.getValidDays());
								shopClient.setMemberEndDate(date);
							}else{
								shopClient.setMemberDate(null);
								shopClient.setMemberEndDate(null);
							}

							if (memberCard.getIsPresentCoupon() == Is.YES.toIntValue()) {
								if (memberCard.getCouponsId() != null) {
									couponsService.insert(userId, memberCard.getCouponsId());
								}
							}
							
							shopClientDAO.insert(shopClient);

							break;
						}
					}
				}
			}
		} else {
			MemberCard card = null;
			if(StringUtils.isNotBlank(shopClient.getMemberCardId())){
				card = memberCardDAO.query(shopClient.getMemberCardId());
			}
			ordersTransactionInfoBO = ordersDAO.countUserTransaction(userId,csId,isChain, shopClient.getClientDate());
			// 用户的会员卡过期，回退一个等级。如果时间过期状态没变，则判定是否要降级或者失效会员卡
			if (shopClient.getMemberEndDate().compareTo(new Date()) < 0
					&& shopClient.getClientStatus() == ShopClientStatus.MEMBER.toIntStatus()) {
				// 如果是最小
				if (shopClient.getGrade() == null
						|| shopClient.getGrade() <= MemberLevelCode.STAIR.toIntValue()) {
					
					// 如果是购买会员卡失效，则统计相应规则属于哪个按等级发放会员卡标准
					if ( card!=null && card.getType() == MemberCardType.TWO_LEVEL.toIntValue()) {
						//
						ordersTransactionInfoBO = ordersDAO.countUserTransaction(userId, csId,isChain,
								shopClient.getCreatedTime());
						MemberCard accordWith = null;
						for (int i = 0, t = memberCardList.size(); i < t; i++) {
							MemberCard memberCard = memberCardList.get(i);
							if (memberCard.getType() == MemberCardType.ONE_LEVEL.toIntValue()) {
								if (memberCard.getBuyCount() != null && memberCard.getBuyCount() > 0) {
									// 用户的累积交易次数 大于 该会员卡的可获得的交易次数
									if (ordersTransactionInfoBO.getCountTransaction() > memberCard.getBuyCount()) {
										receive = true;
									} else {
										receive = false;
										logger.info(userId + "：用户累积交易次数不符合[" + csId + "]重定义等级的会员卡领取标准");
										continue;
									}
								}
								if (memberCard.getConsumePrice() != null && memberCard.getConsumePrice() > 0) {
									// 用户的累计交易金额 大于 该会员卡的可获得的交易金额数
									if (ordersTransactionInfoBO.getSumPayMoney() != null
											&& ordersTransactionInfoBO.getSumPayMoney() > 0 && ordersTransactionInfoBO
													.getSumPayMoney() > memberCard.getConsumePrice()) {
										receive = true;
									} else {
										receive = false;
										logger.info(userId + "：用户累积金额次数不符合[" + csId + "]重定义等级的会员卡领取标准");
										continue;
									}
								}
								if (receive) {
									if (accordWith == null) {
										accordWith = memberCard;
									} else {
										if (memberCard.getCardGrade() > accordWith.getCardGrade()) {
											accordWith = memberCard;
										}
									}
								}
							}
						}
						// 购买会员卡 失效变更为 按等级发放会员卡
						if (accordWith != null) {
							
							shopClient.setMemberCardId(accordWith.getId());
							if (accordWith.getValidTimeState() == MemberCardValidTime.FIXED.toIntStatus()) {
								shopClient.setMemberDate(accordWith.getValidStartTime());
								shopClient.setMemberEndDate(accordWith.getValidEndTime());
							} else if (accordWith.getValidTimeState() == MemberCardValidTime.PERIOD.toIntStatus()) {
								shopClient.setMemberDate(now);
								Date date = DateUtil.addDays(now, accordWith.getValidDays());
								shopClient.setMemberEndDate(date);
							}else{
								shopClient.setMemberDate(null);
								shopClient.setMemberEndDate(null);
							}
							shopClient.setGrade(accordWith.getCardGrade());
							shopClientDAO.update(shopClient);
							
						} else {
							shopClient.setMemberCardId(null);
							shopClient.setGrade(MemberLevelCode.ZERO.toIntValue());
							shopClient.setClientStatus(ShopClientStatus.UNMEMBER.toIntStatus());
							shopClientDAO.update(shopClient);
						}
					} else {
						shopClient.setMemberCardId(null);
						shopClient.setGrade(MemberLevelCode.ZERO.toIntValue());
						shopClient.setClientStatus(ShopClientStatus.UNMEMBER.toIntStatus());
						shopClientDAO.update(shopClient);
					}
				} else {
					for (int i = 0, t = memberCardList.size(); i < t; i++) {
						MemberCard memberCard = memberCardList.get(i);
						if (memberCard.getType() == MemberCardType.ONE_LEVEL.toIntValue()) {
							// 不是最小会员卡，则降级
							if (memberCard.getCardGrade() != null && memberCard.getCardGrade() == (shopClient.getGrade() - 1)) {
								
								shopClient.setMemberCardId(memberCard.getId());
								
								if (memberCard.getValidTimeState() == MemberCardValidTime.FIXED.toIntStatus()) {
									shopClient.setMemberDate(memberCard.getValidStartTime());
									shopClient.setMemberEndDate(memberCard.getValidEndTime());
								} else if (memberCard.getValidTimeState() == MemberCardValidTime.PERIOD.toIntStatus()) {
									shopClient.setMemberDate(now);
									Date date = DateUtil.addDays(now, memberCard.getValidDays());
									shopClient.setMemberEndDate(date);
								}else{
									shopClient.setMemberDate(null);
									shopClient.setMemberEndDate(null);
								}
								shopClient.setGrade(memberCard.getCardGrade());
								shopClientDAO.update(shopClient);
								
								break;
							}
						}
					}
				}
			} else {
				//升级流程
				for (int i = 0, t = memberCardList.size(); i < t; i++) {
					MemberCard memberCard = memberCardList.get(i);
					// 不等于用户购买
					if (memberCard.getType() != MemberCardType.TWO_LEVEL.toIntValue()) {
						if (memberCard.getCardGrade() != null && shopClient.getGrade() != null
								&& memberCard.getCardGrade() == (shopClient.getGrade() + 1)) {
							if (memberCard.getBuyCount() != null && memberCard.getBuyCount() > 0) {
								// 用户的累积交易次数 大于 该会员卡的可获得的交易次数
								if (ordersTransactionInfoBO.getCountTransaction() > memberCard.getBuyCount()) {
									receive = true;
								} else {
									receive = false;
									logger.info(userId + "：用户累积交易次数不符合[" + csId + "]下一等级的会员卡领取标准");
									break;
								}
							}
							if (memberCard.getConsumePrice() != null && memberCard.getConsumePrice() > 0) {
								// 用户的累计交易金额 大于 该会员卡的可获得的交易金额数
								if (ordersTransactionInfoBO.getSumPayMoney() != null
										&& ordersTransactionInfoBO.getSumPayMoney() > 0
										&& ordersTransactionInfoBO.getSumPayMoney() > memberCard.getConsumePrice()) {
									receive = true;
								} else {
									receive = false;
									logger.info(userId + "：用户累积金额次数不符合[" + csId + "]下一等级的会员卡领取标准");
									break;
								}
							}
							// 用户已领取过会员卡-->符合该下一等级的会员卡领取
							if (receive) {
								shopClient.setMemberCardId(memberCard.getId());
								
								if (memberCard.getValidTimeState() == MemberCardValidTime.FIXED.toIntStatus()) {
									shopClient.setMemberDate(memberCard.getValidStartTime());
									shopClient.setMemberEndDate(memberCard.getValidEndTime());
								} else if (memberCard.getValidTimeState() == MemberCardValidTime.PERIOD.toIntStatus()) {
									shopClient.setMemberDate(now);
									Date date = DateUtil.addDays(now, memberCard.getValidDays());
									shopClient.setMemberEndDate(date);
								}else{
									shopClient.setMemberDate(null);
									shopClient.setMemberEndDate(null);
								}
								shopClient.setGrade(memberCard.getCardGrade());
								shopClientDAO.update(shopClient);
								
								break;
							}
						}
					}
				}
			}
		}
		return shopClient;
	}

	@Override
	public ResultVO purchaseMemberCard(HttpServletRequest request,PurchaseMemberCardVO vo) {
		/**
		 * 购买会员卡
		 * memberCardHistoryDAO
		 */
		ResultVO result = new ResultVO();
		User user = userDAO.query(vo.getUserId());
		if (user == null) {
			throw new UserNotFoundException("用户没找到！");
		}
		
		MemberCard memberCard = memberCardDAO.query(vo.getMemberCardId());
		if (memberCard.getType() == MemberCardType.TWO_LEVEL.toIntValue()) {
			
			ShopClient shopClient = shopClientDAO.findClientByUserId(vo.getUserId(), vo.getCsId());
			
			if(shopClient==null){
				Date now = new Date();
				//检查会员编号是否超出最大值
				String reservedKey = DIYKey.getReservedKey(vo.getCsId());
				ReservedVO reservedVO = reservedCacheDAO.getHash(reservedKey, ReservedVO.class);
				String maxNumber = null;
				if(reservedVO == null){
					reservedVO = new ReservedVO();
					maxNumber = OrderNumberUtils.cardNumber(null, OrderNumberUtils.SHOP_CLIENT_DIGIT);
				}else{
					maxNumber = OrderNumberUtils.cardNumber(reservedVO.getMaxValue(), OrderNumberUtils.SHOP_CLIENT_DIGIT);
				}
				reservedVO.setMaxValue(maxNumber);
				reservedCacheDAO.addHash(reservedKey, reservedVO);
				
				shopClient = new ShopClient();
				shopClient.setCsId(vo.getCsId());
				shopClient.setUserId(user.getId());
				shopClient.setMemberCardId(null);
				shopClient.setCardNumber(maxNumber);
				shopClient.setBalance(0d);
				shopClient.setNowIntegral(0);
				shopClient.setConsumeIntegral(0);
				shopClient.setGrade(null);
				shopClient.setClientStatus(ShopClientStatus.UNMEMBER.toIntStatus());
				shopClient.setClientDate(now);
				shopClient.setMemberDate(now);
				shopClient.setMemberEndDate(now);
				// 设置状态为有效
				
				shopClient = shopClientDAO.insert(shopClient);
			}

			String orderNumber = OrderNumberUtils.getOrderlNumber();
			MemberCardHistory memberCardHistory = new MemberCardHistory();
			memberCardHistory.setOrderNumber(orderNumber);
			memberCardHistory.setCsId(vo.getCsId());
			memberCardHistory.setShopClientId(shopClient.getId());
			memberCardHistory.setMemberCardId(vo.getMemberCardId());
			memberCardHistory.setStatus(MemberCardHistoryStatus.WAIT.toIntValue());
			memberCardHistoryDAO.insert(memberCardHistory);
			
			// 微信支付
			OrderInfo orderInfo = new OrderInfo();
			orderInfo.setAttach(Constants.WECHAT_ATTACH_FOR_MEMBER_CARD);
			orderInfo.setOutTradeNo(orderNumber);
			orderInfo.setBody(WECHAT_BODY_KEY + "-" + orderNumber);
			orderInfo.setTotalFee(Math.round(memberCard.getPrice() * 100));
			orderInfo.setSpbillCreateIp(RequestUtil.getRealIp(request));
			orderInfo.setOpenId(user.getOpenId());
			orderInfo.setTradeType(vo.getTradeType());
			
			String wechatKey = DIYKey.getWechatCodeKey(vo.getWcId());
			WechatConfig wechatConfig = wechatConfigCacheDAO.getHash(wechatKey, WechatConfig.class);
			if(wechatConfig == null){
				wechatConfig = wechatConfigDAO.getWechatConfigByWcId(vo.getWcId());
				boolean is  = wechatConfigCacheDAO.addHash(wechatKey, wechatConfig);
				if(!is){
					throw new WechatConfigAddException("找不到微信配置");
				}
			}
			
			PayParam payParam = WeChatUtils.getPayParam(orderInfo,wechatConfig);

			Map<String, Object> map = new HashMap<String, Object>();

			map.put("patParam", payParam);
			result.setData(map);
		}
		return result;
	}

	@Override
	public ResultVO findAllByShopIds(List<String> csIds, String userId) {
		ResultVO result = new ResultVO();
		List<MemberCard> list = memberCardDAO.findAllByShopId(csIds, userId);
		result.setData(list);
		return result;
	}

	//充值会员卡
	@Override
	public ResultVO rechargeMemberCard(HttpServletRequest request, RechargeMemberCardVO cardVO) {
		ResultVO result = new ResultVO();
		User user = userDAO.query(cardVO.getUserId());
		if (user == null) {
			throw new UserNotFoundException("用户没找到！");
		}
		// 在商户会员表中取得记录
		ShopClient shopClient = shopClientDAO.findClientByUserId(cardVO.getUserId(), cardVO.getCsId());
		// 取得符合记录的规则
		ChargeRuleBO chargeRuleBO = chargeRuleDAO.getRechargeMoney(cardVO.getMoney());

		String orderNumber = OrderNumberUtils.getOrderlNumber();
		BalanceHistory balanceHistory = new BalanceHistory();
		balanceHistory.setOrderNumber(orderNumber);
		balanceHistory.setClientId(shopClient.getId());
		balanceHistory.setCsId(cardVO.getCsId());
		balanceHistory.setUserId(cardVO.getUserId());
		if (chargeRuleBO != null) {
			balanceHistory.setCouponsId(chargeRuleBO.getGiveCouponsId());
			balanceHistory.setGiveIntegral(chargeRuleBO.getGiveIntegral());
			balanceHistory.setGiveMoney(chargeRuleBO.getGiveMoney());
		}
		balanceHistory.setOperation(BalanceHistoryOperation.STORAGE_VALUE.toIntValue());
		balanceHistory.setStatus(BalanceHistoryStatus.UNPAID.toIntValue());
		balanceHistory.setBalanceChange(cardVO.getMoney());

		balanceHistoryDAO.insert(balanceHistory);

		// 微信支付
		OrderInfo orderInfo = new OrderInfo();
		orderInfo.setAttach(Constants.WECHAT_ATTACH_FOR_BALANCE_HISTORY);
		orderInfo.setOutTradeNo(orderNumber);
		orderInfo.setBody(WECHAT_BODY_KEY + "-" + orderNumber);
		orderInfo.setTotalFee(Math.round(cardVO.getMoney() * 100));
		orderInfo.setSpbillCreateIp(RequestUtil.getRealIp(request));
		orderInfo.setOpenId(user.getOpenId());
		orderInfo.setTradeType(cardVO.getTradeType());
		
		String wechatKey = DIYKey.getWechatCodeKey(cardVO.getWcId());
		WechatConfig wechatConfig = wechatConfigCacheDAO.getHash(wechatKey, WechatConfig.class);
		if(wechatConfig == null){
			wechatConfig = wechatConfigDAO.getWechatConfigByWcId(cardVO.getWcId());
			boolean is  = wechatConfigCacheDAO.addHash(wechatKey, wechatConfig);
			if(!is){
				throw new WechatConfigAddException("找不到微信配置");
			}
		}
		
		PayParam payParam = WeChatUtils.getPayParam(orderInfo,wechatConfig);

		Map<String, Object> map = new HashMap<String, Object>();

		map.put("orderNumber", orderNumber);
		map.put("patParam", payParam);
		result.setData(map);
		return result;
	}

	@Override
	public ResultVO details(String memberCardId) {
		ResultVO result = new ResultVO();
		MemberCard memberCard = memberCardDAO.query(memberCardId);
		result.setData(memberCard);
		return result;
	}

	@Override
	public ResultVO chargeRule(String csId,String userId) {
		ResultVO result = new ResultVO();
		Map<String,Object> map = new HashMap<String,Object>();
		ShopClientBO shopClient = shopClientDAO.details(csId,userId);
		List<ChargeRuleBO> list = chargeRuleDAO.findAll(csId);
		map.put("shopClient", shopClient);
		map.put("chargeRule", list);
		result.setData(map);
		return result;
	}

	@Override
	public ResultVO findClientByUserId(String csId, String userId) {
		ResultVO result = new ResultVO();
		ShopClient shopClient = shopClientDAO.findClientByUserId(userId, csId);
		result.setData(shopClient);
		return result;
	}

}
